// ActionScript file

import common.utils.StringManager;

import configuration.dataObjects.ReceivingPreferenceDO;

import inbound.receiving.components.RcpCntCnt;
import inbound.receiving.dataObjects.ReceiptContainerDO;
import inbound.receiving.dataObjects.ReceiptDetailDO;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.events.ListEvent;
import mx.managers.PopUpManager;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.utils.ArrayUtil;

[Bindable]private var _rcpDtlDO:ReceiptDetailDO;//收货单明细对象
[Bindable]private var _acRcpCnt:ArrayCollection;//已收货托盘列表
private var _iIntRecNum:Number = 0;
private var _xlRcpCnt:XMLList;//已收货托盘列表
private var _acQtyUM:ArrayCollection;		 	
private var _acInvSts:ArrayCollection;
private var _acLocRule:ArrayCollection;
private var _prefDO:ReceivingPreferenceDO = null;
private var _selectedItem:ReceiptContainerDO = null; //选中行
public var mainApp:Object = null; //父窗口

private var _acRcpDtl:ArrayCollection;//收货单明细列表
[Bindable]private var iBaseQty:int;
[Bindable]private var stBaseUM:String;
private var iIndex:int = 0;//用于控制前后移动收货单明细
private var iArrayLen:int;//用于控制前后移动收货单明细
[Bindable]private var _curLPN:String;
[Bindable]private var _curPutLoc:String;
[Bindable]private var _curQty:int;
private var _selectedIndex:int = 0;

public function set InternalReceiptNum(value:Number):void{
	this._iIntRecNum = value;
	ReceivingSvs.GetReceiptDtls(this.parentApplication.SessionID, value);
}

private function initData():void{
	this._acRcpCnt = new ArrayCollection();
	this._acLocRule = new ArrayCollection();
	this._acQtyUM = new ArrayCollection();	
	this._acInvSts = new ArrayCollection();
	
	var wsdl:String = this.parentApplication.AppServer + "ReceivingService.asmx?wsdl";
	ReceivingSvs.loadWSDL(wsdl);
	wsdl = this.parentApplication.AppServer + "InventoryService.asmx?wsdl";
	InventorySvs.loadWSDL(wsdl);
	//wsdl = this.parentApplication.AppServer + "GeneralInforService.asmx?wsdl";
	//GeneralInfoSvs.loadWSDL(wsdl);	 		
	
	//GeneralInfoSvs.GetLocatingRules(this.parentApplication.SessionID);
	//GeneralInfoSvs.GetInventorySts(this.parentApplication.SessionID);
	ReceivingSvs.GetDefaultPref(this.parentApplication.SessionID, null);
	
	//stage.focus = this;
	focusManager.setFocus(this.QUANTITY);
	focusManager.defaultButton = this.btnOK;
	this.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
}

private function onKeyDown(event:KeyboardEvent):void{
	if (event.keyCode == 27) //Escaped
		this.closeWindow(); 
}

//closeWindow    
private function closeWindow():void {    
	PopUpManager.removePopUp(this);    
}

private function bindReceiptDtl(event:ResultEvent):void{
	if (null != event.result){				
		var errMsg:String = event.result as String;
		
		if (errMsg.search("错误") > 0)
			Alert.show(errMsg, "错误");
		else{
			this.btnPrev.enabled = true;
			this.btnNext.enabled = true;
			var xmlObj:XML = new XML(errMsg);
			this._acRcpDtl = ReceiptDetailDO.getReceiptDetails(xmlObj.RECEIPT_DETAIL);
			if (this._acRcpDtl == null || this._acRcpDtl.length < 1){
				Alert.show("错误：没有明细行", "错误");
				return;
			}
			
			this.iArrayLen = this._acRcpDtl.length;
			this.btnPrev.enabled = false;
			
			if (this.iArrayLen <=1){
				this.btnNext.enabled = false;
			}
			
			this._rcpDtlDO = this._acRcpDtl[this.iIndex];
			ReceivingSvs.GetReceiptCont(this.parentApplication.SessionID, this._rcpDtlDO.WAREHOUSE, this._rcpDtlDO.INTERNAL_RECEIPT_NUM);
			InventorySvs.GetItemUMsASC(this.parentApplication.SessionID, this._rcpDtlDO.COMPANY, this._rcpDtlDO.ITEM);
		}
	}
	
}

private function bindQtyUM(event:ResultEvent):void{
	if (event.result != null){
		var errMsg:String = event.result as String;
		if (StringManager.IsErrorMsg(errMsg)){
			Alert.show(errMsg, "错误");
			return;
		}
		
		var xmlObj:XML = new XML(errMsg);
		this._acQtyUM.removeAll();
		for each(var xmlNode:XML in xmlObj.children()){
			_acQtyUM.addItem({label:xmlNode.DESCRIPTION.toString(), data:xmlNode.QUANTITY_UM.toString(), value:xmlNode.CONVERSION_QTY, flag:xmlNode.GROUP_DURING_CHECKIN.toString()});
		}
		this.QUANTITY_UM.dataProvider = _acQtyUM;
		this.QUANTITY_UM.selectedData = this._rcpDtlDO.QUANTITY_UM;
		if (_acQtyUM != null && _acQtyUM.length > 0)
			this.stBaseUM = _acQtyUM[0].data;
	}
}
/*
private function bindInventorySts(event:ResultEvent):void{
	var xmlObj:XML = new XML(event.result.toString());
	
	for each(var xmlNode:XML in xmlObj.children()){
		_acInvSts.addItem({label:xmlNode.DESCRIPTION.toString(), data:xmlNode.IDENTIFIER.toString()});
	}
	this.INVENTORY_STS.dataProvider = _acInvSts;
}

private function bindLocRule(event:ResultEvent):void{
	var xmlObj:XML = new XML(event.result.toString());
	
	for each(var xmlNode:XML in xmlObj.children()){
		_acLocRule.addItem({label:xmlNode.LOCATING_RULE.toString(), data:xmlNode.LOCATING_RULE.toString()});
	}
	this.LOCATING_RULE.dataProvider = _acLocRule;	
}
*/

private function bindReceivingPref(event:ResultEvent):void{
	if (event.result != null){
		var stErr:String = event.result.toString();
		if (stErr.substr(0, 2) == "错误"){
			Alert.show(stErr, "错误");
			return;
		}
		var xmlObj:XML = new XML(event.result.toString());
		var prefDO:ReceivingPreferenceDO = new ReceivingPreferenceDO();
		prefDO.Init(xmlObj.RECEIVING_PREFERENCE[0]);
		
		this.RecvPrefUI.ReceivingPref = prefDO;
	}
}

private function bindReceiptCont(event:ResultEvent):void{
	_acRcpCnt.removeAll();
	if (null != event.result){				
		var errMsg:String = event.result as String;
		
		if (StringManager.IsErrorMsg(errMsg))
			Alert.show(errMsg, "错误");
		else{
			var xmlObj:XML = new XML(errMsg);
			//for each(var xmlNode:XML in xmlObj.RECEIPT_CONTAINER){
			//	_acRcpCnt.addItem(xmlNode);
			//}
			this._acRcpCnt = ReceiptContainerDO.getReceiptContainers(xmlObj.elements());
		}
	}
	this.dgRecCont.dataProvider = _acRcpCnt;
	this.dgRecCont.dgList.verticalScrollPosition = this.dgRecCont.dgList.maxVerticalScrollPosition;
}

private function setLPNFocus(event:CloseEvent):void{				
	//this.focusManager.setFocus(this.LPN);
}
private function onFault(event:FaultEvent):void{
	Alert.show(event.message.toString(), "错误");	
}

private function btnPrev_Click():void{
	if (this.iIndex > 0){
		this.iIndex--;
		this._rcpDtlDO = this._acRcpDtl[this.iIndex];
		InventorySvs.GetItemUMsASC(this.parentApplication.SessionID, this._rcpDtlDO.COMPANY, this._rcpDtlDO.ITEM);
	}
	this.btnNext.enabled=true;
	setButtonState();
}

private function btnNext_Click():void{
	if (this.iIndex < this.iArrayLen-1){
		this.iIndex++;
		this._rcpDtlDO = this._acRcpDtl[this.iIndex];
		InventorySvs.GetItemUMsASC(this.parentApplication.SessionID, this._rcpDtlDO.COMPANY, this._rcpDtlDO.ITEM);
	}
	this.btnPrev.enabled = true;
	setButtonState();				
}

private function setButtonState():void{
	if (this.iIndex == 0)
		this.btnPrev.enabled = false;
	if (this.iIndex == this.iArrayLen-1)
		this.btnNext.enabled = false;
	if (Number(this._rcpDtlDO.OPEN_QTY) <= 0)
		this.btnOK.enabled = false;
	else
		this.btnOK.enabled = true;
}


private function btnCheckIn_Click():void{
	if (Number(this.QUANTITY.text) <= 0){
		Alert.show("请输入有效数量", "错误");
		//this.focusManager.setFocus(this.QUANTITY);
		this.QUANTITY.stage.focus = this.QUANTITY;
		this.QUANTITY.setSelection(0, this.QUANTITY.length);
		return;
	} 
	
	var iConvQty:int = this.QUANTITY_UM.selectedItem.value;
	var iQty:int = Number(this.QUANTITY.text);
	this.iBaseQty = iQty * iConvQty;
	if (iBaseQty > this._rcpDtlDO.OPEN_QTY){
		Alert.show("超出待收数量", "错误");
		this.focusManager.setFocus(this.QUANTITY);
		return;
	}				
	
	var checkInDlg:LPNEntryUI = 
		LPNEntryUI(PopUpManager.createPopUp(this, LPNEntryUI, true)); 
	checkInDlg.CheckInQty = iBaseQty;
	checkInDlg.UMList = this._acQtyUM;
	checkInDlg.RecvPref = this.RecvPrefUI.ReceivingPref;
	checkInDlg.mainApp = this;
	checkInDlg.callbackFunction = checkInLPNs;
	checkInDlg.Initialize();
	
	PopUpManager.centerPopUp(checkInDlg);
	checkInDlg.x = ( this.parentApplication.width - checkInDlg.width ) / 2;
	checkInDlg.y = ( this.parentApplication.height - checkInDlg.height ) / 2;
}

public function checkInLPNs(acLPN:ArrayCollection):void{
	if (acLPN == null || acLPN.length < 1){
		Alert.show("错误：没有托盘可以收货", "错误");
		return;
	}
	var arCheckInDS:Array = new Array();
	for(var i:int = 0; i < acLPN.length; i++){
		this._curLPN = acLPN[i].LPN;
		this._curPutLoc = acLPN[i].PUT_LOC;
		this._curQty = Number(acLPN[i].QUANTITY);
		arCheckInDS.push(this.ReceiptContainer.toString());
	}
	ReceivingSvs.CheckIn(this.parentApplication.SessionID, arCheckInDS, this.RecvPrefUI.RecevPref.toString());
	//this.btnOK.enabled = false;
}  

private function onCheckInResult(event:ResultEvent):void{
	//收货成功，服务器返回NULL值
	if (null == event.result){
		//this.LPN.text = "";
		//var curQty:Number = Number(this._rcpDtlDO.OPEN_QTY) - this.iBaseQty;
		//this._rcpDtlDO.OPEN_QTY = curQty;
		//this._acRcpDtl[this.iIndex].OPEN_QTY = String(curQty);
		ReceivingSvs.GetReceiptCont(this.parentApplication.SessionID, this._rcpDtlDO.WAREHOUSE, this._rcpDtlDO.INTERNAL_RECEIPT_NUM);
		ReceivingSvs.GetReceiptDtls(this.parentApplication.SessionID, this._iIntRecNum);
	}
	else{				
		var errMsg:String;
		errMsg = event.result as String;
		
		if (StringManager.IsErrorMsg(errMsg))
			Alert.show(errMsg, "错误");
	}
	this.btnOK.enabled = true;
	this.dgRecCont.dgList.verticalScrollPosition = this.dgRecCont.dgList.maxVerticalScrollPosition;
}

private function btnLocate_Click():void{
	if (this.dgRecCont.dgList.selectedItem == null){
		Alert.show("请选择需要定位的托盘", "错误");
		return;
	}
	
	var xmlObj:ReceiptContainerDO = this.dgRecCont.dgList.selectedItem as ReceiptContainerDO;
	var iStatus:int = xmlObj.STATUS;
	if (iStatus == 900){
		Alert.show("该托盘已经上架，调整请通过库存管理功能", "错误");
		return;					
	}
	else if (iStatus >= 300){
		Alert.show("该托盘已经定位，如需要重新定位，请先取消定位", "错误");
		return;
	}
	
	var arIntRecCont:Array = new Array();
	arIntRecCont.push(Number(xmlObj.INTERNAL_CONTAINER_NUM));
	ReceivingSvs.LocateReceiptContainers(this.parentApplication.SessionID, arIntRecCont, this.RecvPrefUI.RecevPref.toString());
}

private function btnLocateAll_Click():void{
	this.btnLocate.enabled = false;
	this.btnLocateAll.enabled = false;
	var bError:Boolean = false;
	var arIntRecCont:Array = new Array();
	
	for (var i:int=0; i < this._acRcpCnt.length; i++){
		var xmlObj:ReceiptContainerDO = _acRcpCnt[i];
		if (xmlObj.STATUS >= 300)
			bError = true;
		else
			arIntRecCont.push(xmlObj.INTERNAL_CONTAINER_NUM);
	}
	
	if (arIntRecCont.length > 1){
		ReceivingSvs.LocateReceiptContainers(this.parentApplication.SessionID, arIntRecCont, this.RecvPrefUI.RecevPref.toString());
		if (bError)
			Alert.show("部分托盘状态不在可操作范围内", "信息");
	}
	else{
		Alert.show("没有符合可定位条件的托盘", "错误");
	}
	this.dgRecCont.dgList.verticalScrollPosition = this.dgRecCont.dgList.maxVerticalScrollPosition;
}

private function onLocateResult(event:ResultEvent):void{
	this.btnLocate.enabled = true;
	this.btnLocateAll.enabled = true;
	//定位成功，服务器返回NULL值
	if (null == event.result){
		ReceivingSvs.GetReceiptCont(this.parentApplication.SessionID, this._rcpDtlDO.WAREHOUSE, this._rcpDtlDO.INTERNAL_RECEIPT_NUM);
	}
	else{				
		var errMsg:String = event.result as String;
		Alert.show(errMsg);
	}
	this.dgRecCont.dgList.verticalScrollPosition = this.dgRecCont.dgList.maxVerticalScrollPosition;
}

private function btnUnlocate_Click():void{
	if (this.dgRecCont.dgList.selectedItem == null){
		Alert.show("错误：请选择需要取消的托盘", "错误");
		return;
	}
	
	var xmlObj:ReceiptContainerDO = this.dgRecCont.dgList.selectedItem as ReceiptContainerDO;
	var iStatus:int = xmlObj.STATUS;
	if (iStatus < 300){
		Alert.show("错误：该托盘尚未定位，不需要取消", "错误");
		return;	
	}
	else if (iStatus == 301){
		Alert.show("错误：该托盘已经开始上架，无法取消", "错误");
		return;
	}
	else if (iStatus == 900 && xmlObj.TASK_CREATED == "Y"){
		Alert.show("错误：该托盘已经上架，调整请通过库存管理功能", "错误");
		return;					
	}
	var arIntContNum:Array = new Array();
	arIntContNum.push(Number(xmlObj.INTERNAL_CONTAINER_NUM));
	ReceivingSvs.UnlocateReceiptConts(this.parentApplication.SessionID, arIntContNum);
}

private function btnUnlocateAll_Click():void{
	var bError:Boolean = false;
	var iStatus:int = 0;
	var xmlObj:ReceiptContainerDO = null;
	var arIntContNum:Array = new Array();
	
	for (var i:int=0; i < this._acRcpCnt.length; i++){
		xmlObj = this._acRcpCnt[i] as ReceiptContainerDO;
		iStatus = xmlObj.STATUS;
		if (iStatus < 300 || 
			iStatus == 301 || 
			(iStatus == 900 && xmlObj.TASK_CREATED == "Y"))
			bError = true;
		else
			arIntContNum.push(xmlObj.INTERNAL_CONTAINER_NUM);
	}
	
	if (arIntContNum.length > 1){					 
		ReceivingSvs.UnlocateReceiptConts(this.parentApplication.SessionID, arIntContNum);
		
		if (bError)
			Alert.show("部分托盘状态不在可操作范围内", "信息");
	}
	else{
		Alert.show("没有可以取消定位的托盘", "错误");
	}
	this.dgRecCont.dgList.verticalScrollPosition = this.dgRecCont.dgList.maxVerticalScrollPosition;
	
}

private function onUnlocateResult(event:ResultEvent):void{
	//取消成功，服务器返回NULL值
	if (null == event.result){
		//this.LPN.text = "";
		//this.QUANTITY.text = String(this._rcpDtlDO.OPEN_QTY);
		ReceivingSvs.GetReceiptCont(this.parentApplication.SessionID, this._rcpDtlDO.WAREHOUSE, this._rcpDtlDO.INTERNAL_RECEIPT_NUM);					
	}
	else{				
		var errMsg:String = event.result as String;
		
		if (StringManager.IsErrorMsg(errMsg))
			Alert.show(errMsg, "错误");
	}
	this.dgRecCont.dgList.verticalScrollPosition = this.dgRecCont.dgList.maxVerticalScrollPosition;
}

private function btnCancelCheckIn_Click():void{				
	if (this.dgRecCont.selectedItem == null){
		Alert.show("请选择需要取消的托盘", "错误");
		return;
	}
	
	this._selectedItem = this.dgRecCont.selectedItem as ReceiptContainerDO;
	if (_selectedItem.STATUS >= 300){
		Alert.show("托盘已定位，无法取消收货。请先取消定位。", "错误");
		return;
	}
	var iRecContNum:int = _selectedItem.INTERNAL_CONTAINER_NUM;
	var arIntContNum:Array = new Array();
	arIntContNum.push(iRecContNum);
	
	ReceivingSvs.CancelCheckIn(this.parentApplication.SessionID, arIntContNum);
}

private function btnCancelCheckInAll_Click():void{				 
	var bError:Boolean = false;
	var xmlObj:ReceiptContainerDO = null;
	var arIntContNum:Array = new Array();
	
	for (var i:int=0; i < this._acRcpCnt.length; i++){
		xmlObj = this._acRcpCnt[i] as ReceiptContainerDO;
		if(Number(xmlObj.STATUS) >= 300)
			bError = true;
		else
			arIntContNum.push(xmlObj.INTERNAL_CONTAINER_NUM);
	}
	
	if (arIntContNum.length > 1){					 
		ReceivingSvs.CancelCheckIn(this.parentApplication.SessionID, arIntContNum);
		
		if (bError)
			Alert.show("部分托盘状态不在可操作范围内", "信息");
	}
	else{
		Alert.show("没有可以取消收货的托盘", "错误");
	}
}

private function onCancelCheckInResult(event:ResultEvent):void{
	//取消成功，服务器返回NULL值
	if (null == event.result){
		//var checkInQty:Number = Number(_selectedItem.QUANTITY);
		//var curQty:Number = Number(this._rcpDtlDO.OPEN_QTY) + checkInQty;
		//this._rcpDtlDO.OPEN_QTY = curQty;
		//this._acRcpDtl[this.iIndex].OPEN_QTY = String(curQty);
		//this._acRcpCnt.removeItemAt(this._acRcpCnt.getItemIndex(xmlObj));	
		ReceivingSvs.GetReceiptCont(this.parentApplication.SessionID, this._rcpDtlDO.WAREHOUSE, this._rcpDtlDO.INTERNAL_RECEIPT_NUM);
		ReceivingSvs.GetReceiptDtls(this.parentApplication.SessionID, this._iIntRecNum);
	}
	else{
		var errMsg:String = event.result as String;
		
		if (StringManager.IsErrorMsg(errMsg))
			Alert.show(errMsg, "错误");
	}
}


protected function dgRecCont_itemDoubleClickHandler(event:ListEvent):void
{
	_selectedIndex = event.rowIndex; 
	//var rcpCntDO:ReceiptContainerDO = this.dgRecCont.selectedItem as ReceiptContainerDO;
	var rcpCntDO:ReceiptContainerDO = this._acRcpCnt[this._selectedIndex];
	if (rcpCntDO != null){
		var rcpCntUI:RcpCntCnt = 
			RcpCntCnt(PopUpManager.createPopUp(this.parent, RcpCntCnt, true));   
		
		rcpCntUI.mainApp = this;
		rcpCntUI.callbackFunction = updateContainer; 
		rcpCntUI.ReceiptContainer = rcpCntDO;
		PopUpManager.centerPopUp(rcpCntUI);	
		rcpCntUI.x = ( this.parentApplication.width - rcpCntUI.width ) / 2;
		rcpCntUI.y = ( this.parentApplication.height - rcpCntUI.height ) / 2;
	}
}

private function updateContainer(rcDO:ReceiptContainerDO ):void{
	this._acRcpCnt[this._selectedIndex].LOCATING_RULE = rcDO.LOCATING_RULE;
	this._acRcpCnt[this._selectedIndex].TO_LOCATION = rcDO.TO_LOCATION;
	//this.dgRecCont.selectedItem["LOCATING_RULE"] = rcDO.LOCATING_RULE;
	//this.dgRecCont.selectedItem["TO_LOCATION"] = rcDO.TO_LOCATION;
	
}